//
//  ScenicStoryVC.swift
//  LeTu
//
//  Created by g1 on 2024/1/13.
//

import UIKit

class ScenicStoryVC: BaseViewController, UITextViewDelegate {

    private var viewModel: ScenicStoryVM
    
    // 广告播放
    private var isTemp = false
    
    init(scenicModel: ScenicModel, storyModel: ScenicStoryModel, currentClassifysIndex: Int, isTemp: Bool = false) {
        viewModel = ScenicStoryVM(scenicModel: scenicModel, storyModel: storyModel, currentClassifysIndex: currentClassifysIndex)
        super.init()
        self.isTemp = isTemp
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        
        updateNavInfo()
        getScenicInfo()
        updatePlayInfo()
        
        NotificationCenter.default.addObserver(self, selector: #selector(paymentSuccessNotification), name: NSNotification.Name("PaymentSuccessNotification"), object: nil)

    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        eventHandle()
        
        // 更新播放信息
        updatePlayInfo()
        
        // 记录播放记录
        apiProvider.request(api: .recordStoryNum(storyId: viewModel.storyModel.id)) { json, _, _ in
            MYLog("AAA - ",json)
        }
    }
    @objc private func paymentSuccessNotification() {
        
        // 更新页面信息
        getScenicInfo(isUpdatesStoryList: true)

    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let point = touches.first?.location(in: audioControlBar.speedButton), !audioControlBar.speedButton.point(inside: point, with: event) {
            audioControlBar.speedListView.isHidden = true
        }
    }
    @objc func textViewTapped() {
        audioControlBar.speedListView.isHidden = true
    }
    override func refreshData() {
        super.refreshData()
        
        print("AAAAA - ")
        startloading()
        
        updateNavInfo()
        getScenicInfo()
        updatePlayInfo()
        audioControlBar.exchangeLanguage()
        
        AppAudioManager.shared.restartAudio()
        
        storyListView.reloadList()
        
        stoploading()
    }
    private func eventHandle() {
        
        /// 当前音频播放完成
        AppAudioManager.shared.completePlayBlock = { [weak self] flag, _, storyModel in
            guard let strongSelf = self else { return }
            if flag == true {
                if let storyModel = storyModel {
                    strongSelf.updatePageData(storyModel: storyModel)
                } else {
                    strongSelf.audioControlBar.setIsplaying(isPlaying: false)
                    strongSelf.filmBackView.stopRotationAnimation()
                }
                
                guard strongSelf.storyListView.isHidden == false else { return }
                strongSelf.storyListView.reloadList()
            }
        }
        
        /// 视频总时长更换
        AppAudioManager.shared.prepareToPlayBlock = { [weak self] time in
            guard let strongSelf = self else { return }
            strongSelf.audioControlBar.setTotalTime(time: time)
        }
        
        /// 正在播放进度订阅
        AppAudioManager.shared.playingBlock = { [weak self] currentTime,_ in
            
            guard let strongSelf = self else { return }
            guard strongSelf.audioControlBar.isChangeSlider == false else { return }
            strongSelf.audioControlBar.setCurrentTime(time: AppAudioManager.shared.formatTimeFromSeconds(seconds: currentTime))
            strongSelf.audioControlBar.setSeek(Float(currentTime/AppAudioManager.shared.totalDuration))
            
        }
        
    }
    /// 获取景区信息
    private func getScenicInfo(isUpdatesStoryList: Bool = false) {
        
        viewModel.getScenicDetails { [weak self] dialog in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                if dialog.code == 200 {
                    strongSelf.setBackImgView()
                    if isUpdatesStoryList == true {
                        strongSelf.storyListView.updateViewInfo(scenicModel: strongSelf.viewModel.scenicModel)
                    }
                } else {
                    strongSelf.showMessage(message: dialog.message)
                }
            }
        }
        
    }
    /// 更新导航信息
    private func updateNavInfo() {
        navbar.updateInfo()
        navbar.layoutSubviews()
    }
    /// 更新播放内容
    private func updatePlayInfo() {
        updatePageData(storyModel: viewModel.storyModel)
        updateProgressInfo()
        updateFilmAnimation()
    }
    /// 更新背景图
    private func setBackImgView() {
        backImgView.sd_setImage(with: URL.encodedURL(string: viewModel.scenicModel.picUrl))
        filmImgView.sd_setImage(with: URL.encodedURL(string: viewModel.scenicModel.picUrl))
    }
    /// 更新讲解内容
    private func updatePageData(storyModel: ScenicStoryModel) {
        viewModel.storyModel = storyModel
        navbar.setTitle(LanguageManager.shared.currentLanguage == .zh ? viewModel.storyModel.chineseAudioName : viewModel.storyModel.englishAudioName)
        descLabel.attributed.text = "\(LanguageManager.shared.currentLanguage == .zh ? viewModel.storyModel.chineseText : viewModel.storyModel.englishText, .paragraph(.alignment(.justified), .lineSpacing(1.21)), .foreground(.white), .kern(1.04), .font(kSetPingFangRegular(13)))"
        storyListView.setCurrentPlayStoryModel(storyModel)

    }
    /// 更新胶片动画
    private func updateFilmAnimation() {
        if AppAudioManager.shared.isPlaying {
            filmBackView.startRotationAnimation()
        } else {
            filmBackView.stopRotationAnimation()
        }
        audioControlBar.setIsplaying(isPlaying: AppAudioManager.shared.isPlaying && AppAudioManager.shared.currentStoryModel == viewModel.storyModel)
    }
    /// 更新时长
    private func updateProgressInfo() {
        guard let totalTime = AppAudioManager.shared.getTotalDurationBeforePlay(url: viewModel.storyModel.finalAudioUrl) else { return }
        audioControlBar.setTotalTime(time: Float(totalTime))
    }
    /// 播放音频
    private func playAudio(index: Int, storyModels: [ScenicStoryModel], isForce: Bool = false) {
        if kUserManager.isLogin {
            let storyModel = storyModels[index]
            guard viewModel.scenicModel.listenPermission == true || (viewModel.scenicModel.listenPermission == false && storyModel.payStatus == 0) || isForce == true else { return }
            AppAudioManager.shared.setPlayList(storyModels, currentIndex: index, listenPermission: viewModel.scenicModel.listenPermission)
            
            if storyModels[index] != viewModel.storyModel || isForce == true {
                AppAudioManager.shared.createAudioPlayer(currentIndex: index, pictureUrl: viewModel.scenicModel.picUrl, currentClassifysIndex: viewModel.currentClassifysIndex)
                updatePageData(storyModel: storyModels[index])
            }
        } else {
            showDetailViewController(LoginVC(viewType: .authCode), sender: nil)
        }
    }
    
    // MARK: - UIButtonAction
    override func backAction() {
        super.backAction()
        
        self.filmBackView.stopRotationAnimation()
        AppAudioManager.shared.completePlayBlock = nil
        
        if AppAudioManager.shared.isPlaying == false {
            AppAudioManager.shared.stopAudio()
        }
        
        guard isTemp == true else { return }
        //AppAudioManager.shared.resetInitState()
    }
    @objc private func audioControlBarAction(title: String) {
        
        if title == "播放" {
            if AppAudioManager.shared.isPlaying {
                AppAudioManager.shared.pauseAudio()
            } else {
                if AppAudioManager.shared.currentTime > 0 {
                    AppAudioManager.shared.playAudio()
                } else {
                    AppAudioManager.shared.createAudioPlayer(pictureUrl: viewModel.scenicModel.picUrl, currentClassifysIndex: viewModel.currentClassifysIndex)
                }
            }
        } else if title == "上一首" {
            AppAudioManager.shared.playLastAudio(handle: { [weak self] status in
                guard let strongSelf = self else { return }
                if status == 0 {
                    strongSelf.show(PaymentVC(scenicModel: strongSelf.viewModel.scenicModel), sender: nil)
                } else if status == 1 {
                    guard let currentStoryModel = AppAudioManager.shared.currentStoryModel else { return strongSelf.audioControlBarAction(title: "播放") }
                    strongSelf.updatePageData(storyModel: currentStoryModel)
                }
            })
        } else if title == "下一首" {
            AppAudioManager.shared.playNextAudio(handle: { [weak self] status in
                guard let strongSelf = self else { return }
                if status == 0 {
                    strongSelf.show(PaymentVC(scenicModel: strongSelf.viewModel.scenicModel), sender: nil)
                } else if status == 1 {
                    guard let currentStoryModel = AppAudioManager.shared.currentStoryModel else { return }
                    strongSelf.updatePageData(storyModel: currentStoryModel)
                }
                
            })
        }
        updateFilmAnimation()
        
    }
    
    // MARK: - configUI
    private func configUI() {
        
        view.addSubview(backImgView)
        view.addSubview(visualEffectView)
        view.addSubview(navbar)
        view.addSubview(filmBackView)
        filmBackView.addSubview(filmView)
        filmBackView.addSubview(filmImgView)
        view.addSubview(audioControlBar)
        view.addSubview(descLabel)
        view.addSubview(storyListView)
        
        backImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        visualEffectView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        navbar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Size.navigationBarHeight)
        }
        filmBackView.snp.makeConstraints { make in
            make.width.height.equalTo(getFilmBackViewHeight())
            make.top.equalTo(navbar.snp.bottom).offset(42)
            make.centerX.equalToSuperview()
        }
        filmView.snp.makeConstraints { make in
            make.left.top.equalTo(12)
            make.right.bottom.equalTo(-12)
        }
        filmImgView.snp.makeConstraints { make in
            make.left.top.equalTo(filmView).offset(28)
            make.bottom.right.equalTo(filmView).offset(-28)
        }
        audioControlBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-50)
            make.height.equalTo(132)
        }
        descLabel.snp.makeConstraints { make in
            make.left.equalTo(28)
            make.right.equalTo(-28)
            make.top.equalTo(filmBackView.snp.bottom).offset(32)
            make.bottom.equalTo(audioControlBar.snp.top).offset(-50)
        }
        storyListView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        navbar.backHandle = { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.backAction()
        }
        navbar.languageHandle = { [weak self] in
            guard let strongSelf = self else { return }
            LanguageManager.shared.exchangeLanguage()
        }
        audioControlBar.clickActionHandle = { [weak self] title in
            guard let strongSelf = self else { return }
            strongSelf.audioControlBarAction(title: title)
        }
        audioControlBar.sliderValueEndHandle = { [weak self] value in
            guard let strongSelf = self else { return }
                        
            AppAudioManager.shared.changeAudio(currentTime: Double(value)*AppAudioManager.shared.totalDuration)
            DispatchQueue.main.asyncAfter(wallDeadline: .now()+1) {
                strongSelf.audioControlBar.isChangeSlider = false
            }
        }
        audioControlBar.clickListHandle = { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.storyListView.show()
        }
        storyListView.clickStoryHandle = { [weak self] index, storyModels, isForce in
            guard let strongSelf = self else { return }
            strongSelf.playAudio(index: index, storyModels: storyModels, isForce: isForce)
            strongSelf.updateFilmAnimation()
        }
        setBackImgView()
        storyListView.isHidden = true

        // 添加 UITapGestureRecognizer 来捕获点击事件
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(textViewTapped))
        descLabel.addGestureRecognizer(tapGesture)
        
        view.setNeedsLayout()
        view.layoutIfNeeded()
        filmBackView.layer.cornerRadius = filmBackView.height/2
        filmView.layer.cornerRadius = filmView.height/2
        filmImgView.layer.cornerRadius = filmImgView.height/2

    }
    private func getFilmBackViewHeight() -> CGFloat {
        return iPhoneX ? 258:228
    }
    // 导航
    private lazy var navbar = ScenicStoryNavBar(title: LanguageManager.shared.currentLanguage == .zh ? viewModel.scenicModel.name : viewModel.scenicModel.englishName)
    // 背景
    private lazy var backImgView: UIImageView = {
        let backImgView = UIImageView()
        return backImgView
    }()
    private lazy var visualEffectView: UIVisualEffectView = {
        let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
        return visualEffectView
    }()
    // - 胶片view
    private lazy var filmBackView: RotatingView = {
        let filmBackView = RotatingView(duration: 15)
        filmBackView.backgroundColor = .white.withAlphaComponent(0.15)
        filmBackView.clipsToBounds = true
        return filmBackView
    }()
    private lazy var filmView: UIView = {
        let filmView = UIView()
        filmView.backgroundColor = .black
        filmView.clipsToBounds = true
        return filmView
    }()
    private lazy var filmImgView: UIImageView = {
        let filmImgView = UIImageView()
        filmImgView.contentMode = .scaleAspectFill
        filmImgView.clipsToBounds = true
        return filmImgView
    }()
    // - 描述
    private lazy var descLabel: UITextView = {
        let descLabel = UITextView()
        descLabel.textColor = .white
        descLabel.isEditable = false
        descLabel.backgroundColor = .clear
        descLabel.isSelectable = false
        descLabel.delegate = self
        return descLabel
    }()
    private lazy var audioControlBar = AudioControlBar()
    // 讲解列表
    private lazy var storyListView = ScenicStoryListView(scenicModel: viewModel.scenicModel, currentPlayStoryModel: AppAudioManager.shared.currentStoryModel ?? viewModel.storyModel)

    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
}
